package com.kizitonwose.calendarview.utils;

import ohos.agp.components.AttrSet;

public class AttrUtils {
    public static <T> T getAttrValue(AttrSet attrSet, String attrKey, Object t) {
        Object m = t;
        if (attrSet == null) {
            return (T) m;
        }
        if (attrSet.getAttr(attrKey).isPresent()) {
            if (t instanceof String) {
                m = attrSet.getAttr(attrKey).get().getStringValue();
            } else if (t instanceof Integer) {
                m = attrSet.getAttr(attrKey).get().getIntegerValue();
            }
        }
        return (T) m;
    }

    /**
     * 获取资源文件id 格式 $layout:布局名称
     *
     * @param attrSet
     * @param resourceKey
     * @return id
     */
    public static int getResourceId(AttrSet attrSet, String resourceKey) {
        String errorStr = "请确认布局中是否添加正确的自定义资源文件，格式@layout:布局名称";
        int resourceId = 0;
        if (attrSet.getAttr(resourceKey).isPresent()) {
            String value = attrSet.getAttr(resourceKey).get().getStringValue();
            if (value.contains(":")) {
                try {
                    resourceId = Integer.parseInt(value.substring(value.indexOf(":") + 1));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    System.out.println(errorStr);
                }
            } else {
                try {
                    throw new Exception(errorStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return resourceId;
    }
}
